<?php


namespace EchoPHP\Database;

use EchoPHP\Database\Connections\Connection;
use EchoPHP\Database\Connections\MysqlConnection;
use EchoPHP\Database\Connections\OracleConnection;
use EchoPHP\Database\Connections\SqlServerConnection;
use EchoPHP\Database\Connections\TuxedoConnection;
use EchoPHP\Database\Connectors\MysqlConnector;
use EchoPHP\Database\Connectors\OracleConnector;
use EchoPHP\Database\Connectors\SqlServerConnector;
use EchoPHP\Database\Connectors\TuxedoConnector;
use EchoPHP\Foundation\Application;
use InvalidArgumentException;

class ConnectionFactory {

    protected $container;

    public function __construct(Application $container) {
        $this->container = $container;
    }

    /**
     * 基于配置创建一个PDO连接或者tuxedo连接
     * @param array $config
     * @return Connection
     */
    public function make(array $config) {
        $databaseConnector = $this->createConnectorResolver($config);

        return $this->createConnection($config['driver'], $databaseConnector, $config['database'], $config);
    }

    /**
     * 创建一个数据库连接闭包
     * @param array $config
     * @return \Closure
     */
    protected function createConnectorResolver(array $config) {
        return function () use ($config) {
            return $this->createConnector($config)->connect($config);
        };
    }

    /**
     * 创建一个PDO实例
     * @param array $config
     * @return MysqlConnector|OracleConnector|SqlServerConnector|TuxedoConnector
     */
    protected function createConnector(array $config) {
        if (!isset($config['driver'])) {
            throw new InvalidArgumentException('未定义数据库驱动');
        }

        switch (strtolower($config['driver'])) {
            case 'mysql':
                return new MysqlConnector();
            case 'sqlserver':
                return new SqlServerConnector();
            case 'oracle':
                return new OracleConnector();
            case 'tuxedo':
                return new TuxedoConnector();
        }
        throw new InvalidArgumentException('不支持该数据库驱动[' . $config['driver'] . ']');
    }

    /**
     * 创建数据库连接实例
     * @param $driver
     * @param $connector
     * @param $database
     * @param array $config
     * @return MysqlConnection|OracleConnection|SqlServerConnection
     */
    protected function createConnection($driver, $connector, $database, array $config = []) {
        switch (strtolower($driver)) {
            case 'mysql':
                return new MysqlConnection($connector, $database, $config);
            case 'sqlserver':
                return new SqlServerConnection($connector, $database, $config);
            case 'oracle':
                return new OracleConnection($connector, $database, $config);
            case 'tuxedo':
                return new TuxedoConnection($connector, $database, $config);
        }

        throw new InvalidArgumentException('不支持该数据库驱动[' . $driver . ']');
    }

}